package com.nervenets.web.controller.handler.common;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.nervenets.utils.AESUtils;
import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.StringUtils;
import com.nervenets.web.annotation.NeedValidation;
import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.ApiParams;
import com.nervenets.web.entity.UserToken;
import com.nervenets.web.validation.Type;

public class TokenParams extends ApiParams {
    @NeedValidation(type = Type.NOTEMPTY, description = "用户的token")
    private String token;

    public final long getUserId() {
        // TODO 加入缓存机制，解析过一次的不需要再次解析（REDIS）
        if (idNullable() && StringUtils.isEmpty(token)) {
            return 0;
        }
        return resolveToken(token);
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public static long resolveToken(String token) {
        String tokenJson = null;
        try {
            tokenJson = AESUtils.decryptData(token);
            if (null == tokenJson) return -1;
            UserToken userToken = JSONObject.parseObject(tokenJson, UserToken.class);
            return userToken.getUserId();
        } catch (Exception e) {
            return -1;
        }
    }

    public boolean tokenIllegal() throws Exception {
        try {

            if (idNullable() && StringUtils.isEmpty(token)) {
                return true;
            }

            String tokenJson = AESUtils.decryptData(token);
            if (null == tokenJson) return false;
            UserToken token = JSONObject.parseObject(tokenJson, UserToken.class);

            return JodaUtils.getTimestamp() - token.getTime() <= 604800000;//token7x24小时过期
        } catch (Exception e) {
            System.out.println(token + ",非法请求");
            throw new Exception("非法请求");
        }
    }

    protected boolean idNullable() {
        return false;
    }

}
